import controller.DatabaseServer;
import lombok.extern.slf4j.Slf4j;
import service.impl.DatabaseServiceImpl;
import service.impl.ReplicationServiceImpl;
import service.ReplicationService;
import model.NodeInfo;
import utils.ConfigUtils;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库服务器主启动类
 */
@Slf4j
public class ServerMain {
    
    private static final int DEFAULT_PORT = 8888;
    
    public static void main(String[] args) {
        // 1. 解析命令行参数
        String portArg = null;
        String slavesArg = null;
        for (String arg : args) {
            if (arg.startsWith("--port=")) {
                portArg = arg.substring("--port=".length());
            } else if (arg.startsWith("--slaves=")) {
                slavesArg = arg.substring("--slaves=".length());
            }
        }
        // 2. 读取端口，优先用命令行
        int port;
        if (portArg != null) {
            port = Integer.parseInt(portArg);
        } else {
            port = Integer.parseInt(ConfigUtils.getProperty("server.port"));
        }
        // 3. 读取从节点，优先用命令行
        String slavesStr = slavesArg != null ? slavesArg : ConfigUtils.getProperty("slaves");
        List<NodeInfo> slaveNodes = new ArrayList<>();
        if (slavesStr != null && !slavesStr.isEmpty()) {
            String[] slaveArr = slavesStr.split(",");
            for (String s : slaveArr) {
                // 格式：id@host:port
                String[] parts = s.split("@");
                String[] hostPort = parts[1].split(":");
                String host = hostPort[0];
                int slavePort = Integer.parseInt(hostPort[1]);
                slaveNodes.add(new NodeInfo(host, slavePort));
            }
        }
        // 4. 初始化ReplicationService
        ReplicationService replicationService = new ReplicationServiceImpl();
        replicationService.initialize(slaveNodes);
        // 5. 注入到DatabaseServiceImpl
        DatabaseServiceImpl db = DatabaseServiceImpl.getInstance();
        db.setReplicationService(replicationService);
        // 自动判断主从角色
        model.NodeRole nodeRole = utils.ConfigUtils.getNodeRole();
        if (nodeRole == model.NodeRole.SLAVE) {
            db.setIsMaster(false);
            log.info("当前节点为SLAVE，只读模式");
        } else {
            db.setIsMaster(true);
            log.info("当前节点为MASTER，读写模式");
        }
        // 6. 启动数据库服务
        DatabaseServer server = new DatabaseServer(port);
        server.start();
    }
} 